package com.wpx.log.core.after;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.wpx.log.core.LogContext;
import com.wpx.log.core.LogRequestContext;
import com.wpx.log.core.annotation.OpLog;
import com.wpx.log.util.Utils;

/**
 * 取新对象值,默认是 参数agrs[0]
 */
@Component
public class TakeNewObjectAfter implements IAfter{
	
	@Autowired
	private EvaluationContext beanFactoryEvaluationContext;
	
	@Override
	public void execute(LogContext logContext, LogRequestContext requestContext, ProceedingJoinPoint point) {

		OpLog opLogAnnotation = requestContext.getOpLogAnnotationAsMethod();
		String newObjEl = opLogAnnotation.newObj();
		if(StringUtils.isEmpty(newObjEl)) {
			Object[] args = requestContext.getPoint().getArgs();
			if(args.length > 0) {
				requestContext.setNnew(args[0]);
			}
			return;
		}
		
		Object takeObject = takeObject(requestContext, newObjEl);
		requestContext.setNnew(takeObject);
		
	}
	
	/**
	 * 补充参数，并执行bean的方法 取到 对象
	 */
	private Object takeObject(LogRequestContext requestContext, String expressionString) {
		String value = requestContext.parseArgsExpression(expressionString);						
		return Utils.getValue(beanFactoryEvaluationContext, value, true);
	}
}
